package cn.robot.board.net;

import android.os.AsyncTask;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Get请求
 */
public final class GetAsyncTask extends AsyncTask<String, Integer, String> {

    private Map<String, String> headers;
    private CallBackListener    mCallBackListener;

    private String getRemoteInfo(String url) {
        String jsonData = null;
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    // .retryOnConnectionFailure(true)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder.url(url).get().build();
            try (Response response = client.newCall(request).execute()) {
                if (response != null && response.body() != null) {
                    jsonData = response.body().string();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonData;
    }

    @Override
    protected String doInBackground(String... params) {
        String ret = null;
        if (params != null) {
            ret = getRemoteInfo(params[0]);
        }
        return ret;
    }

    @Override
    protected void onPostExecute(String s) {
        if (mCallBackListener != null) {
            if (s != null) {
                mCallBackListener.onFinish(s);
            } else {
                mCallBackListener.onError("结果为空");
            }
        }
    }

    /**
     * 接口回调
     *
     * @param callBackListener 回调接口
     */
    public void setCallBackListener(CallBackListener callBackListener) {
        this.mCallBackListener = callBackListener;
    }

    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }
}